package cn.chendd.example;

import junit.framework.TestCase;
import org.apache.commons.jci.compilers.CompilationResult;
import org.apache.commons.jci.compilers.JavaCompiler;
import org.apache.commons.jci.compilers.JavaCompilerFactory;
import org.apache.commons.jci.problems.CompilationProblem;
import org.apache.commons.jci.readers.FileResourceReader;
import org.apache.commons.jci.stores.FileResourceStore;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;

/**
 * @author chendd
 * @date 2019/6/8 13:07
 * 包含外部引用jar中class的引用
 */
public class ExternalClassCompiler extends TestCase {

    public void testSimpleExternalClassCompiler() throws Exception {

        String sources[] = new String[] { "cn/chendd/examples/SimpleExternalClass.java" };
        File sourceDir = new File("D:\\test\\compiler");
        File targetDir = new File("D:\\test\\compiler");
        JavaCompiler compiler = new JavaCompilerFactory().createCompiler("eclipse");
        String jarPath = "C:\\Users\\chendd\\.m2\\repository\\mysql\\mysql-connector-java" +
                "\\5.1.30\\mysql-connector-java-5.1.30.jar";
        URL urls[] = new URL[]{
                new File(jarPath).toURI().toURL()
        };

        ClassLoader classloader = new URLClassLoader(urls);
        CompilationResult result = compiler.compile(sources, new FileResourceReader(sourceDir),
                new FileResourceStore(targetDir) , classloader);
        CompilationProblem[] errors = result.getErrors();
        System.out.println(errors.length + " errors");
        if(errors.length > 1){
            System.out.println(Arrays.toString(errors));
        }
        System.out.println(result.getWarnings().length + " warns");
    }

}
